package com.hackcloud.shardingjdbc.sharding;

import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.*;

public class ComplexShardingStrategyColumns implements ComplexKeysShardingAlgorithm {
    @Override
    public Collection<String> doSharding(Collection collection, ComplexKeysShardingValue complexKeysShardingValue) {
        List<String> tables = new ArrayList<>();
        Map map = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        Object service_flow_no = map.get("service_flow_no");
        int serviceFlowNoIndex = getShardingValueServiceFlowNo(map.get("service_flow_no"));
        int certNoIndex = getShardingValueCertNo(map.get("cert_no"));
        String logicTableName = complexKeysShardingValue.getLogicTableName();
        if (serviceFlowNoIndex == certNoIndex && serviceFlowNoIndex >= 0) {
            tables.add(logicTableName + "_" + serviceFlowNoIndex);
        } else if (certNoIndex >= 0) {
            tables.add(logicTableName + "_" + certNoIndex);
        } else if (serviceFlowNoIndex >= 0) {
            tables.add(logicTableName + "_" + serviceFlowNoIndex);
        } else {
            return collection;
        }
        System.out.println(tables);
        return tables;
    }

    private String getShardingValue(Object shardingObject) {
        if (shardingObject instanceof LinkedList) {
            List<String> shardingList = (List) (shardingObject);
            return shardingList.get(0);
        }
        return shardingObject.toString();
    }

    private int getShardingValueCertNo(Object value) {
        if (value != null) {
            String shardingValue = getShardingValue(value);
            String hashCode = String.valueOf(shardingValue.hashCode());
            String suffix = hashCode.substring(hashCode.length() - 3);
            return Integer.valueOf(suffix) % 2;
        }
        return -1;
    }

    private int getShardingValueServiceFlowNo(Object value) {
        if (value != null) {
            String shardingValue = getShardingValue(value);
            String hashCode = String.valueOf(shardingValue);
            String suffix = hashCode.substring(hashCode.length() - 3);
            return Integer.valueOf(suffix) % 2;
        }
        return -1;
    }

}
